package cn.me.alphamq.broker.config;

import cn.me.alphamq.broker.cache.Container;
import cn.me.alphamq.broker.constant.BrokerConstant;
import cn.me.alphamq.common.model.broker.CommitLogTopicModel;
import cn.me.alphamq.common.util.FileUtil;
import cn.me.alphamq.common.config.GlobalProperties;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

import java.util.concurrent.TimeUnit;

/**
 * CommitLog 的 topic 信息的加载（和定时写入）类
 *
 * @author f
 */
public class TopicLoader {

    /**
     * topic 的 json 配置文件的路径
     */
    private String topicFilePath;

    /**
     * 加载 topic 的信息到内存中
     */
    public void loadProperties() {
        topicFilePath = GlobalProperties.getAlphaMqHome() + BrokerConstant.TOPIC_CONFIG_PATH;
        Container.setCommitLogTopicModelList(
                JSON.parseArray(FileUtil.readFromFile(topicFilePath), CommitLogTopicModel.class)
        );
    }

    /**
     * 开启刷新内存到磁盘的任务
     */
    public void startRefreshTopicInfoTask() {
        CommonThreadPoolConfig.refreshTopicInfoExecutor.execute(() -> {
            while (true) {
                try {
                    // 休眠
                    TimeUnit.SECONDS.sleep(BrokerConstant.REFRESH_TOPIC_TIME_STEP);

                    // 刷新 topic 的配置文件
                    FileUtil.overWriteToFile(topicFilePath,
                            JSON.toJSONString(Container.getCommitLogTopicModelList(), JSONWriter.Feature.PrettyFormat));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

}
